package com.tarena.lbs.marketing.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.api.UpdateParam;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.api.AdminApi;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.marketing.repository.ActivityRepository;
import com.tarena.lbs.marketing.service.ActivitiService;
import com.tarena.lbs.pojo.attach.dto.AttachDTO;
import com.tarena.lbs.pojo.attach.query.AttachQuery;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.marketing.bo.MarketingActivityBO;
import com.tarena.lbs.pojo.marketing.query.MarketingActivityQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivitiServiceImpl implements ActivitiService {
    @Autowired
    private AdminApi adminApi;
    @Autowired
    private AttachApi attachApi;
    @Autowired
    private ActivityRepository activityRepository;


    @Override
    public BasePageList<MarketingActivityBO> activityPage(MarketingActivityQuery query) throws BusinessException {
        UserPrinciple userPrinciple = getUserPrinciple();
        AdminDTO adminDetail = adminApi.getAdminDetail(userPrinciple.getId());
        if (adminDetail==null){
            throw new BusinessException("109","找不到商家信息");
        }
        //填补query
        query.setBusinessId(adminDetail.getBusinessId());
        return activityRepository.getActivitiesByPage(query);
    }

    @Override
    public void activitySave(MarketingActivityBO bo) throws BusinessException{
        UserPrinciple userPrinciple = getUserPrinciple();
        AdminDTO adminDetail = adminApi.getAdminDetail(userPrinciple.getId());
        if (adminDetail==null){
            throw new BusinessException("109","找不到商家信息");
        }
        bo.setBusinessId(adminDetail.getBusinessId());
        bo.setCreateAt(new Date());
        bo.setUpdateAt(bo.getCreateAt());
        bo.setStatus(0);//status 状态 三种以上 过期 未开始 进行中 爆满...
        bo.setEnableStatus(0);//开启状态 0启用 1禁用
        bo.setRewardType(1);
        //UNDO 检验时间 前端结束时间在当前时间之前的点
        bo.setId(activityRepository.activitySave(bo));
        //最后一步,处理图片绑定
        bindActivityPictures(bo);
    }

    @Value("${attach.url.prefix}")
    private String urlPrefix;
    @Override
    public MarketingActivityBO activityDetail(Integer id) {
        //1. 调用仓储层查询本地数据
        MarketingActivityBO bo=activityRepository.getActivitiesById(id);
        //2. 根据查询的结果 调用attach接口 获取当前活动的所有图片信息
        AttachQuery query=new AttachQuery();
        query.setBusinessId(id);
        query.setBusinessType(400);
        List<AttachDTO> attaches = attachApi.getAttachInfoByParam(query);
        //3. 封装图片的url http://localhost:9081/static
        List<String> imgPics=null;
        if (CollectionUtils.isNotEmpty(attaches)){
            imgPics=attaches.stream().map(dto->{
                //http://localhost:9081/static/3579DCC21AD742C3A16773CFAD780C85.png
                String url=urlPrefix+dto.getFileUuid();
                return url;
            }).collect(Collectors.toList());
        }else{
            //不报错了,就是没有活动图片
            imgPics=new ArrayList<>();
        }
        //给活动bo封装图片数组
        bo.setImgPics(imgPics);
        return bo;
    }

    private void bindActivityPictures(MarketingActivityBO bo) throws BusinessException {
        Integer bizId=bo.getId();
        Integer bizType=400;//活动图片
        //1. 从bo拿到图片id字符串并且做解析 知道一共有几章图片绑定 每张图片id是什么
        String[] imgIds = bo.getImgIds().split(",");
        //2. 循环id数组 封装接口的入参
        List<UpdateParam> attachParams=null;
        if (imgIds!=null&& imgIds.length>0){
            //远程调用参数
            attachParams=new ArrayList<>();
            for (String imgId : imgIds) {
                UpdateParam param=new UpdateParam();
                param.setId(Integer.valueOf(imgId));
                param.setBusinessId(bizId);
                param.setBusinessType(bizType);
                attachParams.add(param);
            }
            //3. 调用接口 拿到返回值
            boolean result = attachApi.batchUpdateBusiness(attachParams);
            if (!result){
                throw new BusinessException("110","图片绑定失败");
            }
        }else {
            //图片是空的
            throw new BusinessException("111","图片数据是空的");
        }
    }

    private UserPrinciple getUserPrinciple() throws BusinessException {
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        if (userPrinciple == null){
            throw new BusinessException("101","用户认证解析失败");
        }
        return userPrinciple;
    }
}
